#include "CxlUtil.h"
#include "voiceChedaoji.h"
#include "hal_gps_libuv.h"

static uv_loop_t *loop;
static uv_timer_t halGpsIntervalReq;
static uv_timer_t mainWorkSetTimeOut;
static uv_timer_t reRegisterSetTimeOut;
static uv_timer_t halGpsSpeedTimer;
// static uv_timer_t halGpsSpeedZeroTimer;
static uv_stream_t *serverStream;
static uv_tcp_t halGps_socket;
static uv_connect_t client;

void halGpsLoopInit()
{
    loop = getLoop();
    uv_timer_init(loop, &halGpsIntervalReq);
    uv_timer_init(loop, &mainWorkSetTimeOut);
    uv_timer_init(loop, &reRegisterSetTimeOut);
    uv_timer_init(loop, &halGpsSpeedTimer);
    // uv_timer_init(loop, &halGpsSpeedZeroTimer);
}

void halGpsInterval(void *cb, void *param, uint16_t time)
{
    halGpsIntervalReq.data = param;
    uv_timer_start(&halGpsIntervalReq, cb, 0, time);
}

void halGpsClearInterval()
{
    uv_timer_stop(&halGpsIntervalReq);
}

void halGpsConnect(const char *ip, int port, uv_connect_cb cb)
{
    uv_tcp_init(loop, &halGps_socket);

    struct sockaddr_in dest;
    uv_ip4_addr(ip, port, &dest);

    uv_tcp_connect(&client, &halGps_socket, (const struct sockaddr *)&dest, cb);
    audioNetConnecting();
}

uv_connect_t *gethalGpsClientConnect()
{
    return &client;
}

void halGpsMainWorkSetTimeout(void *cb, uint16_t time)
{
    if (uv_timer_get_due_in(&mainWorkSetTimeOut) > 0)
    {
        return;
    }
    else
    {
        uv_timer_start(&mainWorkSetTimeOut, cb, time, 0);
    }
}

void halGpsReRegisterSetTimeout(void *cb, uint16_t time)
{
    if (uv_timer_get_due_in(&reRegisterSetTimeOut) > 0)
    {
        return;
    }
    else
    {
        uv_timer_start(&reRegisterSetTimeOut, cb, time, 0);
    }
}

void halGpsSpeedTimerStop()
{
    uv_timer_stop(&halGpsSpeedTimer);
}

void halGpsSpeedTimerSet(void *cb, uint16_t time)
{
    if (uv_timer_get_due_in(&halGpsSpeedTimer) > 0)
    {
        return;
    }
    else
    {
        uv_timer_start(&halGpsSpeedTimer, cb, time, 0);
    }
}

// void halGpsSpeedZeroTimerStop()
// {
//     uv_timer_stop(&halGpsSpeedZeroTimer);
// }

// void halGpsSpeedZeroTimerSet(void *cb, uint16_t time)
// {
//     if (uv_timer_get_due_in(&halGpsSpeedZeroTimer) > 0)
//     {
//         return;
//     }
//     else
//     {
//         uv_timer_start(&halGpsSpeedZeroTimer, cb, time, 0);
//     }
// }